<template>
  <div class="app-container">
    <el-tabs type="border-card" style="height:100%" class="flex-cloumn">
      <el-tab-pane label="结果对比" class="flex-cloumn">
        <div style="width: 100%" shadow="always" class="comparer-top-card"> 
          <el-row style="display: flex;align-items: center;">
            <div class="comparer-top-contain">
                <el-row style="display: flex;">
                    <el-tag
                        size="m"
                        type="primary"
                        class="mx-1 mr10"
                        effect="dark"
                      >
                      报告一
                    </el-tag>
                    <versionReportForm class="demo-form-inline flex_1" v-model:version="report1.version" v-model:report="report1.id"/>
                </el-row>
                <el-row style="display: flex;">
                  <el-tag
                    size="m"
                    type="primary"
                    class="mx-1 mr10"
                    effect="dark"
                  >
                    报告二
                  </el-tag>
                  <versionReportForm class="demo-form-inline flex_1" v-model:version="report2.version" v-model:report="report2.id"/>
                </el-row>
            </div>
            <div>
              <el-button size="large" type="primary" v-hasPermi="['testmanage:compareResult:compare']" @click="compareResult">对比</el-button>
            </div>
          </el-row>
        </div>
        <el-divider content-position="left"></el-divider>
        <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="68px">
          <el-form-item label="接口名称" style="width: 240px" prop="infName">
            <el-input
                v-model="queryParams.infName"
                placeholder="请输入接口名称"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="结果" style="width: 240px" prop="compareResult">
            <dictCombox v-model="queryParams.compareResult" prop="compareResult"
              dictType="compareType"
              placeholder="请选择结果"></dictCombox>
          </el-form-item>
          <el-form-item>
              <el-button v-hasPermi="['testmanage:compareResult:list']" type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          </el-form-item>
          <jsonDiffKit/>
        </el-form>
        <xTable ref="infTableRef" refId="infTableRef" :data="infList" border 
            @selection-change="handleSelectionChange" v-loading="loading" :showCheckBox="false">
            <template #columList>
                <el-table-column label="接口名称" align="left" prop="infName" :show-overflow-tooltip="true"/>
                <!-- <el-table-column label="接口编码" align="left" prop="infCode" :show-overflow-tooltip="true"/> -->
                <el-table-column label="接口路径" align="left" prop="infUrl" :show-overflow-tooltip="true"/>
                <el-table-column label="方法类型" align="center" prop="infMethod" :show-overflow-tooltip="true">
                  <template #default="scope">
                    <dict-tag :options="infMethod" :value="scope.row.infMethod"/>
                  </template>
                </el-table-column>
                <el-table-column label="结果" prop="compareResult" align="center">
                  <template #default="scope">
                    <dict-tag :options="compareType" :value="scope.row.compareResult"/>
                  </template>
                </el-table-column>
                <el-table-column label="信息" prop="compareMsg" align="left" :show-overflow-tooltip="true">
                </el-table-column>
                <el-table-column label="操作" fixed="right" align="center">
                  <template #default="scope">
                      <el-link type="primary" @click="openDetail(scope.row)" :underline="false">详情</el-link>  
                  </template>
                </el-table-column>
            </template>
        </xTable>
        <el-dialog :close-on-click-modal="false" title="结果对比" v-model="resultOpen" width="80%"
                append-to-body>
                <el-row>
                  <el-col :span="12" style="flex: '1'">
                    <el-descriptions :column="2" border>
                      <el-descriptions-item label="版本号:">{{resultList[0].version  }}</el-descriptions-item>
                      <el-descriptions-item label="测试报告:">{{ resultList[0].reportName }}</el-descriptions-item>
                      <el-descriptions-item label="接口名称:">{{ resultList[0].infName }}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                  <el-col :span="12" style="flex: '1'">
                    <el-descriptions :column="2" border>
                      <el-descriptions-item label="版本号:">{{resultList[1].version  }}</el-descriptions-item>
                      <el-descriptions-item label="测试报告:">{{ resultList[1].reportName }}</el-descriptions-item>
                      <el-descriptions-item label="接口名称:">{{ resultList[1].infName }}</el-descriptions-item>
                    </el-descriptions>
                  </el-col>
                </el-row>
                <div class="diff-result">
                  <!-- <JsonEditorVue v-model="diffResult"
                    style="width: 100%;  height: 70vh; margin-top:5px"
                    class="editor"
                    :current-mode="code">
                  </JsonEditorVue> -->
                  <!-- <div v-if="diffResult">
                    <pre :style="{ color: 'red' }">{{ diffResult }}</pre>
                  </div> -->
                  <div ref="result" id="result" v-html="diffResult"></div>
                  <jsonDiff ref="jsonDiffRef"/>
                </div>
                <!-- <el-row>
                  <el-col :span="12">
                    <JsonEditorVue v-model="resultList[0].result"
                      style="width: 100%;  height: 70vh; margin-top:5px"
                      class="editor"
                      :current-mode="code">
                    </JsonEditorVue>
                  </el-col>
                  <el-col :span="12">
                    <JsonEditorVue v-model="resultList[1].result"
                      style="width: 100%;  height: 70vh; margin-top:5px"
                      class="editor"
                      :current-mode="code">
                    </JsonEditorVue>
                  </el-col>
                </el-row> -->
                <!-- <template #footer>
                    <div class="dialog-footer">
                        <el-button type="primary" @click="close">关 闭</el-button>
                    </div>
                </template> -->
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="结果查看" class="flex-cloumn">
        <viewResult/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script setup name="CompareResult">
import {getCurrentInstance, reactive, ref} from "vue";
import versionReportForm from './component/versionReportForm'
const {proxy} = getCurrentInstance();
import { getReportByVersion } from "@/api/testmanage/report";
import { compare } from "@/api/testmanage/compare";
import { isNotVoid, isVoid } from "@/utils/util";
import JsonEditorVue from 'json-editor-vue3'
import jsonDiff from './jsonDiff/index.vue'
import viewResult from './component/viewResult'

// import jsondiffpatch from 'jsondiffpatch'
// const instance = jsondiffpatch.create({
//     objectHash: function(obj, index) {
//     if (typeof obj._id !== 'undefined') {
//         return obj._id;
//     }
//     if (typeof obj.id !== 'undefined') {
//         return obj.id;
//     }
//     if (typeof obj.name !== 'undefined') {
//         return obj.name;
//     }
//     return '$$index:' + index;
//     },
// });
const {infMethod, compareType} = proxy.useDict("infMethod", "compareType");


const infList = ref([]);
const totalList = ref([]);
const loading = ref(false);
const report1Loading = ref(false);
const report2Loading = ref(false);
const report1Options = ref([]);
const report2Options = ref([]);
const resultOpen = ref(false);
const resultList = ref([]);
const diffResult = ref('');
const data = reactive({
  report1: {
    version: '',
    id: ''
  },
  report2: {
    version: '',
    id: ''
  },
  queryParams: {
    infName: '',
    compareResult: ''
  }
});

const {report1, report2, queryParams} = toRefs(data);

onMounted(() => {

})

function compareResult() {
  loading.value = true
  if (isVoid(report1.value.id) || isVoid(report2.value.id)) {
    proxy.$modal.msgError("请选择报告");
    loading.value = false
    return
  } 
  if(report1.value.id === report2.value.id) {
    proxy.$modal.msgError("请选择两个不同的报告");
    loading.value = false
    return
  }
  let list = [ report1.value.id,report2.value.id ]
  compare(list).then(response => {
    if (response.code === 200) {
      infList.value = response.result
      totalList.value = response.result
    } else {
      proxy.$modal.msgError(response.msg);
    }
    loading.value = false
  });
}

function handleSelectionChange() {
  
}

function compareJSON(obj1, obj2, path = '') {
  if(!obj1 || !obj2){
    return ''
  }
  // 检查类型是否一致
  if (typeof obj1 !== typeof obj2) {
    return `<p style="color: red;">${path} - 类型不一致</p>`;
  }

  // 检查对象是否为基本类型
  if (typeof obj1 !== 'object' || obj1 === null || obj2 === null) {
    if (obj1 !== obj2) {
      return `<p style="color: red;">${path} - 值不一致</p>`;
    }
    return '';
  }

  let result = '';

  // 遍历对象的属性
  for (let key in obj1) {
    if (obj1.hasOwnProperty(key)) {
      // 递归比较属性值
      result += compareJSON(obj1[key], obj2[key], path + '. ' + key);
    }
  }
  return result;
}

function openDetail(row) {
  resultOpen.value = true
  resultList.value = row.resultList
  resultList.value.forEach(item=>{
    if(Object.prototype.toString.call(item.result) === "[object String]"){
      item.result = JSON.parse(item.result);
    }
    item.infName = row.infName
  })
  // const diff = jsondiffpatch.diff(resultList.value[0].result, resultList.value[1].result)
  // diffResult.value = JSON.stringify(diff, null, 2)
  // const delta = jsondiffpatch.diff(resultList.value[0].result, resultList.value[1].result)
  // diffResult.value = delta
  if (resultList.value.length == 1) {
    resultList.value.push({})
  }
  if (isNotVoid(resultList.value[0].result) && isNotVoid(resultList.value[1].result)) {
    diffResult.value = compareJSON(resultList.value[0].result, resultList.value[1].result);
  }else{
    diffResult.value=''
  }
  nextTick(()=>{
    proxy.$refs.jsonDiffRef?.diffJson({oldStr:resultList.value[0].result,newStr:resultList.value[1].result})
  })
}

function close() {
  resultOpen.value = false
}

function handleQuery() {
  let list = totalList.value
  if (isNotVoid(queryParams.value.infName) && isNotVoid(queryParams.value.compareResult)) {
    let infName = queryParams.value.infName
    infList.value = list.filter((item) => item.infName.search(infName) != -1)
    let result = queryParams.value.compareResult
    infList.value = infList.value.filter((item) => item.compareResult == result)
    return
  }
  if (isNotVoid(queryParams.value.infName)) {
    let infName = queryParams.value.infName
    infList.value = list.filter((item) => item.infName.search(infName) != -1)
    return
  }
  if (isNotVoid(queryParams.value.compareResult)) {
    let result = queryParams.value.compareResult
    infList.value = list.filter((item) => item.compareResult == result)
    return
  }
  infList.value = list
}

</script>

<style scoped lang="scss">

.diff-result {
  margin-top: 20px;
}
.comparer-top-card{
  padding: 15px;
  .comparer-top-contain{
    .el-row:last-child{
      :deep(.el-form-item){
        margin-bottom: 0 !important;
      }
    }
  }
  .el-select{
    width: 100%;
  }
}
:deep(.el-tabs__content){
  flex:1;
  .el-tab-pane{
    height:100%;
  }
}
</style>
